package cn.tedu._08security.config;

import cn.tedu._08security.service.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;

/**
 * Spring Security配置类
 * EnableGlobalMethodSecurity注解: 激活鉴权功能;
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    /*
        将UserDetailsServiceImpl对象注册到IoC容器;
        用户Security框架调用loadUserByUsername()方法查询用户信息;
     */
    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.
                authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/api/public/**").permitAll() //无需认证的请求
                        .anyRequest().authenticated() //其它请求需要认证
                )
                .formLogin(form -> form
                        .permitAll() //允许表单登录
                )
                .logout(logout -> logout
                        .permitAll() //允许退出登录
                );

        return http.build();
    }
}











